<template>
    <div class="barrage">
        <div class="card" ref="scrollContainer">
            <p class="message" v-if="messageInfo" v-for="i in messageInfo">
            <p v-if="i.Ifs == true" class="name">{{ i.name + " | 斗鱼等级：" + i.level + " | 粉丝牌等级：" + i.fsLevel }}</p>
            <p v-else class="name">{{ i.name + " | 斗鱼等级：" + i.level }}</p>
            <p class="content" v-if="i.Ifs == true" style="background-color:#409EFF;color:#ffffff">{{ i.text }}</p>
            <p class="content" v-else>{{ i.text }}</p>
            </p>
        </div>
    </div>
</template>

<script>
import { message, notification } from 'ant-design-vue';
import { reactive, onBeforeUnmount, h } from 'vue';
import Tools from '@/plugin/tools'

export default {
    data() {
        return {
            messageInfo: null,
            websocket: new WebSocket('wss://danmuproxy.douyu.com:8506/')
        }
    },
    methods: {
        message(str) {
            var len = str.length;
            var buffer = new ArrayBuffer(len + 12);
            new DataView(buffer).setInt16(0, len + 8, true);
            new DataView(buffer).setInt16(4, len + 8, true);
            new DataView(buffer).setInt16(8, 45314, false);
            var bufView = new Uint8Array(buffer, 12);
            for (var i = 0; i < len; i++) {
                bufView[i] = str.charCodeAt(i);
            }
            return buffer;
        },
        livemessage(type, contents) {
            if (type == "success") {
                var config = {
                    content: contents,
                    key: "live",
                }
                message.success(config)
            }
            if (type == "loading") {
                var config = {
                    content: contents,
                    key: "live",
                }
                message.loading(config)
            }
            if (type == "info") {
                var config = {
                    content: contents,
                    key: "live",
                }
                message.info(config)
            }
            if (type == "error") {
                var config = {
                    content: contents,
                    key: "live",
                }
                message.error(config)
            }
        },
        joinlive(type, contents, avatar) {
            if (type == "success") {
                var config = {
                    icon: h('img', {
                        src: avatar,
                        style: 'border-radius:50%;width:30px;'
                    }),
                    message: "直播间消息",
                    description: contents,
                    key: "live",
                    duration: 3,
                    placement: 'bottom',
                    maxCount: 3
                }
                notification.success(config)
            }
            if (type == "info") {
                var config = {
                    icon: h('img', {
                        src: avatar,
                        style: 'border-radius:50%;width:30px;'
                    }),
                    message: "直播间消息",
                    description: contents,
                    key: "live",
                    duration: 3,
                    placement: 'bottom',
                    maxCount: 3
                }
                notification.info(config)
            }
            if (type == "error") {
                var config = {
                    icon: h('img', {
                        src: avatar,
                        style: 'border-radius:50%;width:30px;'
                    }),
                    message: "直播间消息",
                    description: contents,
                    key: "live",
                    duration: 3,
                    placement: 'bottom',
                    maxCount: 3
                }
                notification.error(config)
            }
        }
    },
    created() {
        this.livemessage("loading", "加入直播间中")

        onBeforeUnmount(() => {
            if (this.websocket !== undefined & this.websocket !== null) {
                this.websocket.close();
            }
        })

        var sounds = [];
        var i = 0;
        var that = this

        // 筛选内容
        function getStrMiddle(str, before, after) {
            let m = str.match(new RegExp(before + '(.*?)' + after));
            return m ? m[1] : false;
        }

        // 类型
        function getType(str) {
            return getStrMiddle(str, "type@=", "/");
        }
        // uid
        function getUID(data) {
            let uid = getStrMiddle(data, "uid@=", "/");
            return Number(uid)
        }
        // 用户
        function getName(data) {
            let name = getStrMiddle(data, "nn@=", "/");
            return name
        }
        // 头像
        function getAvatar(data) {
            if (getType(data) == "chatmsg" | getType(data) == "uenter") {
                let txt = getStrMiddle(data, "ic@=", "/")
                let str = txt.split('@S')
                let avatar = `https://apic.douyucdn.cn/upload/${str.join('/')}_big.jpg`
                return avatar;
            }
        }
        // 头像
        function getText(data) {
            let txt = getStrMiddle(data, "txt@=", "/")
            return txt;
        }
        // 斗鱼等级
        function getDYLevel(data) {
            let Level = getStrMiddle(data, "level@=", "/");
            return Number(Level)
        }
        // 是否拥有粉丝牌
        function getifs(data) {
            if (getType(data) == "chatmsg") {
                let ifs = getStrMiddle(data, "ifs@=", "/");
                if (Number(ifs) == 1) {
                    return true
                } else {
                    return false
                }
            }
        }

        // 粉丝牌等级
        function getFsPLevel(data) {
            if (getType(data) == "chatmsg") {
                let ifs = getifs(data);
                if (ifs == true) {
                    let bl = getStrMiddle(data, "bl@=", "/");
                    return Number(bl)
                }
            }
        }

        this.websocket.onopen = () => {
            that.livemessage("success", "加入直播间成功")
            var str = 'type@=loginreq/roomid@=762505/dfl@=/username@=visitor8243989/uid@=1132317461/ver@=20230728/aver@=218101901/ct@=0/' + '\0';
            var buffer = that.message(str);
            this.websocket.send(buffer);
            var str1 = "type@=joingroup/rid@=762505/gid@=-99999/" + "\0";
            var buffer1 = that.message(str1);
            setTimeout(() => {
                this.websocket.send(buffer1);
            }, 1000);
            setInterval(() => {
                this.websocket.send(that.message("type@=mrkl/" + '\0'));
            }, 45000);
        };
        this.websocket.onmessage = (event) => {
            var reader = new FileReader();
            reader.onload = function () {
                var text = reader.result;
                const receivedMessage = text;

                var m = receivedMessage.toString()

                if (getDYLevel(m) > 5 & getName(m) != "" & getText(m) == "") {
                    if (getType(m) == "uenter") {
                        let text = getName(m) + "进入直播间"
                        that.joinlive("info", text, getAvatar(m))
                    }
                }
                if (getDYLevel(m) > 5 & getName(m) != "" & getText(m) != "") {
                    Tools.DataTime()
                        .then((datatime) => {
                            if (getType(m) == "chatmsg") {
                                if (sounds[i] != "") {
                                    sounds[i] = sounds[i] || {};
                                    if (getifs(m) == true) {
                                        sounds[i] = {
                                            uid: getUID(m),
                                            name: getName(m),
                                            text: getText(m),
                                            level: getDYLevel(m),
                                            Ifs: getifs(m),
                                            fsLevel: getFsPLevel(m),
                                            time: datatime
                                        }
                                    } else {
                                        sounds[i] = {
                                            uid: getUID(m),
                                            name: getName(m),
                                            text: getText(m),
                                            level: getDYLevel(m),
                                            Ifs: getifs(m),
                                            time: datatime
                                        }
                                    }
                                }
                                sounds = sounds.filter(item => item != null);
                            }
                            sounds = sounds.filter(item => item != null);
                            that.messageInfo = sounds
                        })
                }

                i++
            };
            reader.readAsText(event.data);
            if (that.$refs.scrollContainer !== undefined & that.$refs.scrollContainer !== null) {
                if (that.$refs.scrollContainer.scrollTop !== undefined & that.$refs.scrollContainer.scrollTop !== null & that.$refs.scrollContainer.scrollHeight !== undefined & that.$refs.scrollContainer.scrollHeight !== null) {
                    that.$refs.scrollContainer.scrollTop = that.$refs.scrollContainer.scrollHeight
                }
            }
        };

        this.websocket.onclose = () => {
            console.log("ok");
        };
    },
    mounted() {
        onBeforeUnmount(() => {
            if (this.websocket !== undefined & this.websocket !== null) {
                this.websocket.close();
            }
        })
    }
}

</script>

<style scoped lang="scss">
.barrage {
    .card {
        .message {
            .content {
                position: relative;
                display: inline-block;
                padding: 10px;
                background-color: #f2f2f2;
                border-radius: 10px;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            }

            margin-left: 10px;
        }

        margin: 24px;
        width: 800px;
        height: 600px;
        overflow: hidden;
        overflow-y: scroll;
        border-radius: 12px;
        box-shadow: 0 0 10px 0 rgba($color: #000000, $alpha: 0.3);
        display: flex;
        flex-direction: column;
        align-items: self-start;
    }

    .card::-webkit-scrollbar {
        width: 0rem;
        /* 设置滚动条宽度为非常小的值 */
        background-color: transparent;
        /* 设置滚动条背景色为透明 */
    }

    width: 100%;
    height: 100%;
    position: relative;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

@media screen and (max-width: 800px) {
    .barrage {
        .card {
            .message {
                .content {
                    position: relative;
                    display: inline-block;
                    padding: 10px;
                    background-color: #f2f2f2;
                    border-radius: 10px;
                    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
                }

                margin-left: 10px;
            }

            margin: 24px;
            width: 100%;
            height: 600px;
            overflow: hidden;
            overflow-y: scroll;
            border-radius: 12px;
            box-shadow: 0 0 10px 0 rgba($color: #000000, $alpha: 0.3);
            display: flex;
            flex-direction: column;
            align-items: self-start;
        }

        .card::-webkit-scrollbar {
            width: 0rem;
            /* 设置滚动条宽度为非常小的值 */
            background-color: transparent;
            /* 设置滚动条背景色为透明 */
        }

        width: 100%;
        height: 100%;
        position: relative;
        top: 0;
        bottom: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
}
</style>